import { useRef } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, DatePicker, Popconfirm, Radio, Select, Table, Tag } from 'antd';
import { Dayjs } from 'dayjs';
import { observer } from 'mobx-react-lite';

import Des from '@/components/des';
import Dict from '@/components/dict';
import Filter from '@/components/filter';
import SearchInput from '@/components/search-input';
import Text from '@/components/text';

import { useStore } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { LogoutTypeObj } from '@/enum/log';
import { loginLogKick, loginLogPage } from '@/services/base/quanxianmokuaidenglurizhiguanli';
import { formatDate, formatValue } from '@/utils';

import Detail, { DetailRef } from './detail';

/** 该模块增删改查对象 */
export type BizObject = BASE.LoginLog;

const Page: React.FC = () => {
  const store = useStore();
  const permission = usePermission();
  const detail = useRef<DetailRef>(null);
  const [filter] = Filter.useForm();
  const table = useAntdTable(
    async ({ current, pageSize }, { id, loginTime, outTime, ...formData }) => {
      const [loginBeginTime, loginEndTime] = ((loginTime as [Dayjs?, Dayjs?]) || []).map((v) =>
        v?.format('YYYY-MM-DD HH:mm:ss')
      );
      const [outBeginTime, outEndTime] = ((outTime as [Dayjs?, Dayjs?]) || []).map((v) =>
        v?.format('YYYY-MM-DD HH:mm:ss')
      );

      const res = await loginLogPage({
        ...formData,
        ...id,
        loginBeginTime,
        loginEndTime,
        outBeginTime,
        outEndTime,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/* 筛选 */}
      <Filter onFinish={onSearch} form={filter}>
        <Filter.Item name="id">
          <SearchInput
            style={{
              width: 120 * 3
            }}
            typeList={[
              { value: 'username', children: '用户名' },
              { value: 'fullName', children: '用户姓名' }
            ]}
          />
        </Filter.Item>

        <Filter.Item name="onlineFlag">
          <Select
            style={{
              width: 120
            }}
            allowClear
            placeholder="是否在线"
            options={[
              { label: '在线', value: true },
              { label: '离线', value: false }
            ]}
          />
        </Filter.Item>

        <Filter.Item name="clientType">
          <Radio.Group>
            {(store.dict['clientType'] || []).map((item) => {
              return (
                <Radio value={item.dicValue} key={item.dicValue}>
                  {item.dicName}
                </Radio>
              );
            })}
          </Radio.Group>
        </Filter.Item>

        <Filter.Item name="loginTime">
          <DatePicker.RangePicker showTime placeholder={['登录开始时间', '登录结束时间']} />
        </Filter.Item>

        <Filter.Item name="outTime">
          <DatePicker.RangePicker showTime placeholder={['退出开始时间', '退出结束时间']} />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: 'id',
            dataIndex: 'id'
          },
          {
            title: '请求用户',
            render: (_, r) => {
              if (String(r.userId) === '0') {
                return emptyText;
              }

              return (
                <Des>
                  <Des.Item label="用户id" value={formatValue(r.userId)} />
                  <Des.Item
                    label="用户类型"
                    value={<Dict dicCode="userType" value={r.userType} />}
                  />
                  <Des.Item label="用户姓名" value={formatValue(r.fullName)} />
                  <Des.Item label="用户名" value={formatValue(r.username)} />
                  <Des.Item label="token" value={formatValue(r.token)} />
                </Des>
              );
            }
          },

          {
            title: '终端信息',
            render: (_, r) => {
              return (
                <Des>
                  <Des.Item label="请求IP" value={formatValue(r.loginIp)} />
                  <Des.Item label="浏览器" value={formatValue(r.browser)} />
                  <Des.Item
                    label="客户端类型"
                    value={<Dict dicCode="clientType" value={r.clientType} />}
                  />
                  <Des.Item label="操作系统" value={formatValue(r.systemName)} />
                  <Des.Item label="城市" value={formatValue(r.loginCity)} />
                </Des>
              );
            }
          },
          {
            title: '时间',
            render: (_, r) => {
              return (
                <Des>
                  <Des.Item label="登录时间" value={formatDate(r.loginTime)} />
                  <Des.Item label="登出时间" value={formatDate(r.logoutTime)} />
                  <Des.Item label="失效时间" value={formatDate(r.expireTime)} />
                  <Des.Item label="创建时间" value={formatDate(r.createTime)} />
                </Des>
              );
            }
          },
          {
            title: '状态',
            render: (_, r) => {
              return (
                <Des>
                  <Des.Item
                    label="在线状态"
                    value={
                      r.online ? <Tag color="green">在线</Tag> : <Tag color="default">离线</Tag>
                    }
                  />
                  <Des.Item
                    label="登出方式"
                    value={formatValue(LogoutTypeObj.get(r.logoutType!)?.text)}
                  />
                  <Des.Item label="登出说明" value={formatValue(r.logoutExplain)} />
                </Des>
              );
            }
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        detail.current?.open({
                          rowData: row
                        });
                      }}
                      type="primary"
                    >
                      详情
                    </Text>
                  )}

                  {row.online && permission.check() && (
                    <Popconfirm
                      title={`是否强制将该账户下线？`}
                      onConfirm={async () => {
                        const res = await loginLogKick({
                          id: row.id as unknown as number
                        });

                        store.app?.message.success(res.message);
                        table.refresh();

                        return res.success;
                      }}
                    >
                      <Text type="danger">强制下线</Text>
                    </Popconfirm>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Detail ref={detail} />
    </>
  );
};

export default observer(Page);
